package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-manager2/cache"
	"novel-manager2/moderls"
	"novel-manager2/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	redis_key := "login_err" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}

	var user moderls.User
	err := moderls.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名错误或密码不正确",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {

		cache.Rdb.Incr(cache.Ctx, redis_key)

		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)

			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁两个小时",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return

}

func List(c *gin.Context) {
	var article []moderls.Article

	redis_key := "list"

	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}

	moderls.DB.Find(&article)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": article,
	})
	return
}

func Detail(c *gin.Context) {

	id := c.Query("id")

	var article []moderls.Article

	redis_key := "list" + id

	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}

	moderls.DB.Find(&article)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": article,
	})
	return
}
